<template>
  <div class="activity-manage">
    <div class="page-header">
      <h1>文化活动管理</h1>
      <button @click="showAddDialog = true" class="add-btn">
        <span class="btn-icon">➕</span>
        添加活动
      </button>
    </div>

    <div class="search-bar">
      <input 
        v-model="searchKeyword" 
        @input="searchActivities"
        placeholder="搜索活动名称..." 
        class="search-input"
      >
    </div>

    <div class="activities-table">
      <table>
        <thead>
          <tr>
            <th>ID</th>
            <th>活动名称</th>
            <th>描述</th>
            <th>开始日期</th>
            <th>结束日期</th>
            <th>地点</th>
            <th>详情</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="activity in filteredActivities" :key="activity.id">
            <td>{{ activity.id }}</td>
            <td class="name-cell">{{ activity.title }}</td>
            <td class="desc-cell">{{ activity.mainDescription.substring(0, 50) }}...</td>
            <td class="date-cell">{{ formatDate(activity.startDate) }}</td>
            <td class="date-cell">{{ formatDate(activity.endDate) }}</td>
            <td class="location-cell">{{ activity.location }}</td>
            <td class="actions-cell">
              <button @click="showDetails(activity)" class="details-btn">查看详情</button>
            </td>
            <td class="actions-cell">
              <button @click="editActivity(activity)" class="edit-btn">编辑</button>
              <button @click="deleteActivity(activity.id)" class="delete-btn">删除</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 添加/编辑对话框 -->
    <div v-if="showAddDialog || showEditDialog" class="dialog-overlay" @click="closeDialog">
      <div class="dialog" @click.stop>
        <div class="dialog-header">
          <h2>{{ showAddDialog ? '添加活动' : '编辑活动' }}</h2>
          <button @click="closeDialog" class="close-btn">✕</button>
        </div>
        <div class="dialog-body">
          <form @submit.prevent="saveActivity">
            <div class="form-group">
              <label>活动名称：</label>
              <input v-model="currentActivity.title" type="text" required>
            </div>
            <div class="form-group">
              <label>描述：</label>
              <textarea v-model="currentActivity.mainDescription" rows="4" required></textarea>
            </div>
            <div class="form-group">
              <label>开始日期：</label>
              <input v-model="currentActivity.startDate" type="date" required>
            </div>
            <div class="form-group">
              <label>结束日期：</label>
              <input v-model="currentActivity.endDate" type="date" required>
            </div>
            <div class="form-group">
              <label>地点：</label>
              <input v-model="currentActivity.location" type="text" required>
            </div>

            <!-- Details Editor -->
            <div class="details-editor">
              <div class="details-header">
                <h3>活动详情</h3>
                <button @click.prevent="addDetail" class="add-detail-btn">添加详情</button>
              </div>
              <div v-for="(detail, index) in currentActivity.details" :key="index" class="detail-item-editor">
                <input v-model="detail.subtitle" placeholder="子标题 (例如: 活动特色)" class="detail-input">
                <textarea v-model="detail.content" placeholder="详细内容" rows="3" class="detail-textarea"></textarea>
                <button @click.prevent="removeDetail(index)" class="remove-detail-btn">✕</button>
              </div>
            </div>

            <div class="form-actions">
              <button type="button" @click="closeDialog" class="cancel-btn">取消</button>
              <button type="submit" class="save-btn">保存</button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- 详情对话框 -->
    <div v-if="showDetailsDialog" class="dialog-overlay" @click="closeDetailsDialog">
      <div class="dialog" @click.stop>
        <div class="dialog-header">
          <h2>{{ selectedActivity?.title }} - 详细信息</h2>
          <button @click="closeDetailsDialog" class="close-btn">✕</button>
        </div>
        <div class="dialog-body details-body">
          <div v-if="selectedActivity?.details && selectedActivity.details.length > 0">
            <div v-for="(detail, index) in selectedActivity.details" :key="index" class="detail-item">
              <h3>{{ detail.subtitle }}</h3>
              <p>{{ detail.content }}</p>
            </div>
          </div>
          <div v-else>
            <p>暂无更多详细信息。</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'

interface ActivityDetail {
  subtitle: string;
  content: string;
}

interface Activity {
  id?: number
  title: string
  mainDescription: string
  startDate: string
  endDate: string
  location: string
  details?: ActivityDetail[];
}

const activities = ref<Activity[]>([])
const filteredActivities = ref<Activity[]>([])
const searchKeyword = ref('')
const showAddDialog = ref(false)
const showEditDialog = ref(false)
const showDetailsDialog = ref(false)
const selectedActivity = ref<Activity | null>(null)

const currentActivity = ref<Activity>({
  title: '',
  mainDescription: '',
  startDate: '',
  endDate: '',
  location: '',
  details: []
})

const loadActivities = async () => {
  try {
    const response = await fetch('http://localhost:8080/api/cultural-activities')
    if (response.ok) {
      activities.value = await response.json()
      filteredActivities.value = activities.value
    }
  } catch (error) {
    console.error('加载活动数据失败:', error)
    alert('加载活动数据失败')
  }
}

const searchActivities = () => {
  if (!searchKeyword.value.trim()) {
    filteredActivities.value = activities.value
  } else {
    filteredActivities.value = activities.value.filter(activity =>
      activity.title.toLowerCase().includes(searchKeyword.value.toLowerCase())
    )
  }
}

const formatDate = (dateStr: string) => {
  if (!dateStr) return '未设置'
  return new Date(dateStr).toLocaleDateString('zh-CN')
}

const editActivity = (activity: Activity) => {
  currentActivity.value = JSON.parse(JSON.stringify(activity)); // Deep copy for safe editing
  if (!currentActivity.value.details) {
    currentActivity.value.details = [];
  }
  showEditDialog.value = true
}

const showDetails = (activity: Activity) => {
  selectedActivity.value = activity;
  showDetailsDialog.value = true;
}

const closeDetailsDialog = () => {
  showDetailsDialog.value = false;
  selectedActivity.value = null;
}

const addDetail = () => {
  if (!currentActivity.value.details) {
    currentActivity.value.details = [];
  }
  currentActivity.value.details.push({ subtitle: '', content: '' });
}

const removeDetail = (index: number) => {
  if (currentActivity.value.details) {
    currentActivity.value.details.splice(index, 1);
  }
}

const deleteActivity = async (id: number | undefined) => {
  if (id === undefined) {
    alert('无法删除，活动ID未知。')
    return
  }
  if (!confirm('确定要删除这个活动吗？')) return

  try {
    const response = await fetch(`http://localhost:8080/api/cultural-activities/${id}`, {
      method: 'DELETE'
    })
    
    if (response.ok) {
      alert('删除成功')
      loadActivities()
    } else {
      alert('删除失败')
    }
  } catch (error) {
    console.error('删除活动失败:', error)
    alert('删除活动失败')
  }
}

const saveActivity = async () => {
  try {
    const url = showAddDialog.value 
      ? 'http://localhost:8080/api/cultural-activities'
      : `http://localhost:8080/api/cultural-activities/${currentActivity.value.id}`
    
    const method = showAddDialog.value ? 'POST' : 'PUT'
    
    const response = await fetch(url, {
      method,
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(currentActivity.value)
    })
    
    if (response.ok) {
      alert(showAddDialog.value ? '添加成功' : '更新成功')
      closeDialog()
      loadActivities()
    } else {
      alert(showAddDialog.value ? '添加失败' : '更新失败')
    }
  } catch (error) {
    console.error('保存活动失败:', error)
    alert('保存活动失败')
  }
}

const closeDialog = () => {
  showAddDialog.value = false
  showEditDialog.value = false
  currentActivity.value = {
    title: '',
    mainDescription: '',
    startDate: '',
    endDate: '',
    location: '',
    details: []
  }
}

onMounted(() => {
  loadActivities()
})
</script>

<style scoped>
.activity-manage {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.page-header h1 {
  color: #2c3e50;
  margin: 0;
}

.add-btn {
  display: flex;
  align-items: center;
  padding: 10px 20px;
  background: #27ae60;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
  transition: background-color 0.3s;
}

.add-btn:hover {
  background: #229954;
}

.btn-icon {
  margin-right: 8px;
}

.search-bar {
  margin-bottom: 20px;
}

.search-input {
  width: 100%;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
}

.activities-table {
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  overflow: hidden;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

th {
  background: #f8f9fa;
  font-weight: 600;
  color: #2c3e50;
}

.name-cell {
  font-weight: 500;
  color: #2c3e50;
}

.desc-cell {
  color: #666;
  max-width: 200px;
}

.date-cell {
  color: #3498db;
  font-size: 14px;
}

.location-cell {
  color: #27ae60;
}

.actions-cell {
  white-space: nowrap;
}

.details-btn {
  background: #1abc9c;
  color: white;
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  margin-right: 8px;
}

.details-btn:hover {
  background: #16a085;
}

.edit-btn, .delete-btn {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  margin-right: 8px;
}

.edit-btn {
  background: #3498db;
  color: white;
}

.edit-btn:hover {
  background: #2980b9;
}

.delete-btn {
  background: #e74c3c;
  color: white;
}

.delete-btn:hover {
  background: #c0392b;
}

.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0,0,0,0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.dialog {
  background: white;
  border-radius: 10px;
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.dialog-header h2 {
  margin: 0;
  color: #2c3e50;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #999;
}

.close-btn:hover {
  color: #666;
}

.dialog-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
  color: #2c3e50;
}

.form-group input,
.form-group textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
}

.form-group textarea {
  resize: vertical;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 30px;
}

.cancel-btn, .save-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
}

.cancel-btn {
  background: #95a5a6;
  color: white;
}

.cancel-btn:hover {
  background: #7f8c8d;
}

.save-btn {
  background: #27ae60;
  color: white;
}

.save-btn:hover {
  background: #229954;
}

.details-body {
  max-height: 60vh;
  overflow-y: auto;
}

.detail-item {
  margin-bottom: 20px;
}

.detail-item h3 {
  color: #2c3e50;
  margin-bottom: 8px;
  border-left: 3px solid #1abc9c;
  padding-left: 10px;
}

.detail-item p {
  color: #666;
  line-height: 1.6;
  white-space: pre-wrap;
}

.details-editor {
  margin-top: 20px;
  padding: 15px;
  border: 1px solid #eee;
  border-radius: 8px;
}

.details-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.details-header h3 {
  margin: 0;
  color: #2c3e50;
}

.add-detail-btn {
  background: #3498db;
  color: white;
  border: none;
  padding: 8px 12px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.add-detail-btn:hover {
  background: #2980b9;
}

.detail-item-editor {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 6px;
  margin-bottom: 10px;
  position: relative;
}

.detail-input, .detail-textarea {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  margin-bottom: 10px;
}

.detail-textarea {
  resize: vertical;
}

.remove-detail-btn {
  position: absolute;
  top: 10px;
  right: 10px;
  background: #e74c3c;
  color: white;
  border: none;
  border-radius: 50%;
  width: 24px;
  height: 24px;
  cursor: pointer;
  line-height: 24px;
  text-align: center;
  font-weight: bold;
  transition: background-color 0.3s;
}

.remove-detail-btn:hover {
  background: #c0392b;
}
</style> 